package nciae.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import nciae.db.common.CommonResult;
import nciae.db.mapper.ExpertMapper;
import nciae.db.mapper.UserMapper;
import nciae.db.pojo.entity.Expert;
import nciae.db.pojo.entity.User;
import nciae.db.service.ExpertService;
import nciae.db.service.UserService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper mapper;

    @Autowired
    private ExpertService expertService;

    @Autowired
    private ExpertMapper expertMapper;
    @Autowired
    private UserMapper userMapper;


    @Override
    public CommonResult<User> checkUser(String userName, String pwd,HttpSession session) {
        CommonResult rs = new CommonResult();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userName);
        queryWrapper.eq("user_pwd", pwd);
        List<User> list = mapper.selectList(queryWrapper);
        if (list.size() > 0) {
            rs.setCode(0);
            rs.setMsg("登录成功");
            rs.setData(list.get(0));

        }else{
            rs.setCode(-1);
            rs.setMsg("用户名或密码错误");
        }
        return rs;
    }

    @Override
    public User getUserInfo(Integer userId) {
        User user = mapper.selectById(userId);
        return user;
    }

    @Override
    public boolean getUserIsAdmin(Integer id) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.select("role").eq("id", id);
        List<User> list = mapper.selectList(userQueryWrapper);
        if (!list.isEmpty()){
            if (list.get(0).getRole().equals("管理员")){
                return true;
            }
        }

        return false;
    }



    @Override
    public CommonResult<Integer> findUserId(String chargerName) {
        CommonResult<Integer> rs = new CommonResult<>();
        try {
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.select("id").eq("real_name", chargerName);
            List<User> list = mapper.selectList(userQueryWrapper);
            if (list.isEmpty()) {
                rs.setCode(-1);
                rs.setMsg("未找到用户名为 " + chargerName + " 的用户");
                return rs;
            }
            // 假设用户 id 是 Integer 类型，如果是 Long 类型，请相应修改
            Integer userId = list.get(0).getId();
            rs.setCode(0);
            rs.setMsg("查询成功");
            rs.setData(userId);
            return rs;
        } catch (Exception e) {
            rs.setCode(-1);
            rs.setMsg("发生错误: " + e.getMessage());
            return rs;
        }
     }

    @Override
    public CommonResult search(String name, String realName,String role,String tel, Integer page, Integer size) {
        CommonResult<List<User>> rs = new CommonResult<>();
        try {
            Page<User> pg = new Page<>(page, size);
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            if (name != null && !name.isEmpty()) {
                queryWrapper.eq("user_name", name);
            }
            if (realName != null && !realName.isEmpty()) {
                queryWrapper.eq("real_name", realName);
            }
            if (role != null && !role.isEmpty()) {
                queryWrapper.eq("role", role);
            }
            if (tel != null && !tel.isEmpty()) {
                queryWrapper.eq("tel", tel);
            }
            mapper.selectPage(pg, queryWrapper);
            List<User> list = pg.getRecords();
            long count = pg.getTotal();
            rs.setCode(0);
            rs.setMsg("查询成功");
            rs.setCount(count);
            rs.setData(list);
            return rs;
        } catch (Exception e) {
            rs.setCode(-1);
            rs.setMsg("发生错误" + e.getMessage());
            return rs;
        }
    }

    @Override
    public CommonResult save(User user) {
        CommonResult rs = new CommonResult();
        User user1 = mapper.selectById(user.getId());
        try {
             // 添加
             if (user.getId() == 0) {
                 if (mapper.selectCount(new QueryWrapper<User>().eq("user_name", user.getUserName())) > 0) {
                     rs.setCode(-1);
                     rs.setMsg("用户名重复");
                 }
                 else {
                     int k = mapper.insert(user);
                     rs.setCode(0);
                     rs.setMsg("添加成功");
                 }
             } else {
                 if(Objects.equals(user1.getUserName(), user.getUserName()))
                 {
                     int k = mapper.updateById(user);
                     rs.setCode(0);
                     rs.setMsg("保存成功");
                 }
                 else{
                     if (mapper.selectCount(new QueryWrapper<User>().eq("user_name", user.getUserName())) > 0) {
                         rs.setCode(-1);
                         rs.setMsg("用户名重复");
                     }
                     else {
                         int k = mapper.updateById(user);
                         rs.setCode(0);
                         rs.setMsg("保存成功");
                     }
                 }
             }
             if (user.getRole()!=null &&user.getRole().equals("指导教师")) {
                 expertService.setUserInfo(user);
             }

            return rs;
        } catch (Exception exception) {
            rs.setCode(-1);
            rs.setMsg("发生错误：" + exception.getMessage());
            return rs;
        }
    }

    @Override
    public CommonResult delete(Integer id) {
        CommonResult rs = new CommonResult();
        User user = mapper.selectById(id);
        Expert expert = expertMapper.selectOne(new QueryWrapper<Expert>().eq("user_name",user.getUserName()));
        try {
            int k = mapper.deleteById(id);
            if (k > 0) {
                rs.setCode(0);
                rs.setMsg("删除成功");
                if (user.getRole() != null && ("指导教师").equals(user.getRole())) {
                    expertService.delete(expert.getId());
                }
            } else {
                rs.setCode(-1);
                rs.setMsg("删除失败");
            }
            return rs;
        } catch (Exception exception) {
            rs.setCode(-1);
            rs.setMsg("发生错误：" + exception.getMessage());
            return rs;
        }
    }

    @Override
    public CommonResult resetPwd(Integer id) {
        CommonResult rs = new CommonResult();
        try {
            User user = mapper.selectById(id);
            user.setUserPwd("123456");
            int k = mapper.updateById(user);
            rs.setCode(0);
            rs.setMsg("重置成功");
            return rs;
        } catch (Exception e) {
            rs.setCode(-1);
            rs.setMsg("发生错误" + e.getMessage());
            return rs;
        }
    }

    @Override
    public CommonResult changePwd(Integer id, String oldPwd, String newPwd) {
        CommonResult rs = new CommonResult();
        User user = mapper.selectById(id);
        if (!user.getUserPwd().equals(oldPwd)) {
            rs.setCode(-1);
            rs.setMsg("原始密码错误");
            return rs;
        }
        user.setUserPwd(newPwd);
        try {
            mapper.updateById(user);
            rs.setCode(0);
            rs.setMsg("修改密码成功");
            return rs;
        } catch (Exception ex) {
            rs.setCode(-2);
            rs.setMsg("发生错误" + ex.getMessage());
            return rs;
        }
    }

    @Override
    public CommonResult<Integer> batchImport(MultipartFile file) {
        CommonResult<Integer> result = new CommonResult<>();
        //文件不能为空
        if (file.isEmpty()) {
            result.setCode(-1);
            result.setMsg("文件为空");
            return result;
        }
        try {
            InputStream inputStream = file.getInputStream();
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);

            int firstRowNum = sheet.getFirstRowNum() + 1;
            int lastRowNum = sheet.getLastRowNum();

            ArrayList<User> users = new ArrayList<>();
            for (int i = firstRowNum; i <= lastRowNum; i++) {
                User user = new User();
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }

                //设置用户名
                Cell UserNameCell = row.getCell(0);
                String userName = UserNameCell.toString();
                if (userName == null || userName.isEmpty()) {
                    user.setUserName("");
                } else {
                    //查询是否重名
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("user_name", userName);
                    List<User> list = mapper.selectList(queryWrapper);
                    if (list.size() > 0) {
                        continue;
                    }
                    user.setUserName(UserNameCell.toString());
                }

                //设置真实姓名
                Cell RealNameCell = row.getCell(1);
                if (RealNameCell == null) {
                    user.setRealName("");
                } else {
                    user.setRealName(RealNameCell.toString());
                }

                //设置密码
                Cell PwdCell = row.getCell(2);
                String pwdStr = PwdCell.toString();
                if (pwdStr == null || pwdStr.isEmpty()) {
                    user.setUserPwd(" ");
                } else {
                    if (PwdCell.getCellType() == CellType.NUMERIC) {
                        pwdStr = BigDecimal.valueOf(PwdCell.getNumericCellValue()).stripTrailingZeros().toPlainString();
                        user.setUserPwd(pwdStr);
                    } else {
                        user.setUserPwd(pwdStr);
                    }
                }

                //设置角色
                Cell RoleCell = row.getCell(3);

                if (RoleCell == null) {
                    user.setRole("");
                } else {
                    user.setRole(RoleCell.toString());
                }

                //设置电话
                Cell TelCell = row.getCell(4);
                String phoneStr = TelCell.toString();
                if (phoneStr == null || phoneStr.isEmpty()) {
                    user.setTel("");
                } else {
                    if (TelCell.getCellType() == CellType.NUMERIC) {
                        phoneStr = BigDecimal.valueOf(TelCell.getNumericCellValue()).stripTrailingZeros().toPlainString();
                        user.setTel(phoneStr);
                    } else {
                        user.setTel(phoneStr);
                    }
                }

                //设置邮箱
                Cell EmailCell = row.getCell(5);
                if (EmailCell == null) {
                    user.setEmail("");
                } else {
                    user.setEmail(EmailCell.toString());
                }

                //设置单位
                Cell DepartmentCell = row.getCell(6);
                if(DepartmentCell == null){
                    user.setDepartment("");
                }else{
                    user.setDepartment(DepartmentCell.toString());
                }

                //设置职称
                Cell TitleCell = row.getCell(7);
                if(TitleCell == null){
                    user.setTitle("");
                }else{
                    user.setTitle(TitleCell.toString());
                }

                //设置简介
                Cell IntroduceCell = row.getCell(8);
                if(IntroduceCell == null){
                    user.setIntroduce("");
                }else{
                    user.setIntroduce(IntroduceCell.toString());
                }
                if(user.getRole() != null && "指导教师".equals(user.getRole())){
                    expertService.setUserInfo(user);
                }
                users.add(user);
            }
            inputStream.close();
            workbook.close();
            for (User user : users) {
//                if (user.getRole().equals("")){
//                    expertService.setUserInfo(user);
//                }
                mapper.insert(user);
            }

            result.setCode(0);
            result.setMsg("导入成功");
            result.setData(users.size());
            return result;
        } catch (Exception e) {
            result.setCode(-2);
            result.setMsg("文件读取失败");
            return result;
        }
    }

    @Override
    public CommonResult<List<String>> listChargerName() {
        CommonResult<List<String>> result = new CommonResult<>();
        try {
            List<String> chargerNamesList = new ArrayList<String>();
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            //根据角色字段查询角色为班主任的用户姓名信息
            queryWrapper.eq("role","班主任");
            List<User> users = mapper.selectList(queryWrapper);
            for (User user:users){
                String realName = user.getRealName();
                chargerNamesList.add(realName);
            }
            result.setCode(0);
            result.setData(chargerNamesList);
            return result;
        }catch (Exception e){
            result.setCode(-1);
            result.setMsg("发生错误"+e.getMessage());
            return result;
        }
    }

    @Override
    public User getLoginUser(HttpSession session) {
        User user = (User) session.getAttribute("user");
        return user;
    }

    @Override
    public CommonResult<List<User>> getUsersByRole(String role) {
        CommonResult<List<User>> result = new CommonResult<>();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role", role);
        List<User> teachers = mapper.selectList(new LambdaQueryWrapper<User>().eq(User::getRole, "班主任"));
        result.setData(teachers);
        result.setCode(0);
        return result;
    }

    @Override
    public Map<String, Integer> getUserCategoryStatistics() {
        List<Map<String, Object>> results = userMapper.countUserCategories();
        Map<String, Integer> statistics = new HashMap<>();
        for (Map<String, Object> result : results) {
            statistics.put(result.get("role").toString(), Integer.parseInt(result.get("count").toString()));
        }
        return statistics;
    }
}
